<template>
  <Modal
    :value="isShow"
    :title="title"
    :closable="true"
    draggable
    @on-visible-change="onVisiableChange"
  >
    <div style="padding: 10px;">
      <!-- <Card :title="`作者： ${book.author}`" :padding="0" shadow> -->
      <CellGroup>
        <Cell title="书名">
          <Input slot="extra" placeholder="必填" v-model="newBook.name" />
        </Cell>
        <Cell title="作者">
          <Input slot="extra" placeholder="必填" v-model="newBook.author" />
        </Cell>
      </CellGroup>
      <!-- </Card> -->
    </div>
    <div slot="footer">
      <Button @click="handleAddBook" style="margin-left: 8px">确认</Button>
    </div>
  </Modal>
</template>
<script>
import { addBook } from '../api/book'
import { addBookToMyBookShelf } from '../api/bookShelf'

export default {
  name: 'UserAddOrEditBook',
  props: {
    isShow: {
      type: Boolean,
      required: true,
      default: false
    },
    title: {
      type: String,
      required: true
    },
    bookId: {
      type: String
    },
    setVisiable: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      book: {},
      newBook: {}
    }
  },
  methods: {
    onVisiableChange (v) {
      this.setVisiable(v)
    },
    handleAddBook () {
      if (this.newBook.name && this.newBook.author) {
        addBook(this.newBook)
          .then(res => {
            this.$Notice.success({
              title: `${res.data.name} 添加成功！`,
              desc: '正在自动加入到您的书架...',
              duration: 5
            })
            addBookToMyBookShelf(res.data._id)
              .then(res => {
                this.$Notice.success({
                  title: '添加成功！',
                  desc: `${res.data.bookName} 已自动加入到您的书架!`,
                  duration: 5
                })
              })
              .catch(err => {
                this.$Notice.error({
                  title: '添加失败,请手动添加',
                  desc: err.response.data.message,
                  duration: 5
                })
              })
            this.setVisiable(false)
          })
          .finally(() => {
            this.newBook = {}
          })
      } else {
        this.$Notice.error({
          title: '添加失败',
          desc: '信息填写不完整，请认真填写',
          duration: 5
        })
      }
    }
  }
}
</script>
